let app = getApp();
const util = require('../../utils/util.js');
let payWay = [{
 "id": 1,
 "package": "余额支付",
 "money": 100
}]
let diner_num = 1;
Page({
 //页面的初始数据
 data: {
  tableNum: "",
  confirmOrder: [],
  // 输入框中的用餐人数，默认为1
  diner_num: 1,
  diner_price: 0,
  // 用餐人数输入框获取焦点
  diner_numF: false,
  // 备注信息
  remarks: "",
  //支付方式列表
  payWayList: [],
  // 购物车数据
  cartList: [],
  totalPrice: 0,
  totalNum: 0,
  balance: 0,
  // 遮罩
  maskFlag: true,
 },
 // 生命周期函数--监听页面加载
 onLoad: function(Options) {
  var that = this;
  var wx_user =  wx.getStorageSync('wx_user');
  if (wx_user == null || wx_user == '') {
    wx.showToast({
      title: '登录信息过期，请登录！',
      icon: 'none',
      duration: 1000,
      success:function(){
        setTimeout(function () {
          //要延时执行的代码,延迟1s
          wx.navigateTo({
            url: '../login/login',
          })
        },1000)
      }
    })   
  }
  let tableNum = Options.tableNum;
  var arr = wx.getStorageSync('cart') || [];
  var buyer = wx.getStorageSync('wx_user');
  for (var i in arr) {
   this.data.totalPrice += arr[i].quantity * arr[i].price;
   this.data.totalNum += arr[i].quantity
  }
  this.setData({
   tableNum: tableNum,
   cartList: arr,
   totalPrice: this.data.totalPrice.toFixed(2),
   totalNum: this.data.totalNum,
   balance: buyer.balance,
   diner_price: diner_num * arr[0].repastMoney
  })
  // wx.getSystemInfo({
  //   success: function (res) {
  //     that.setData({
  //       sliderLeft: (res.windowWidth / that.data.tabs.length - res.windowWidth / 2) / 2,
  //       sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex,
  //     });
  //   }
  // });
 },
 // 点击数字，输入框出现对应数字
 getDinnerNUM: function(e) {
  var dinnerNum = e.currentTarget.dataset.num;
  var diner_num = this.data.diner_num;
  var cart = wx.getStorageSync('cart') || [];
  // 点击“输”，获取焦点
  if (dinnerNum == 0) {
   this.setData({
    diner_numF: true,
   })
   this.getDinerNum();
  } else {
   this.setData({
    diner_num: dinnerNum,
     // 按照人数算出价格
    diner_price: dinnerNum * cart[0].repastMoney
   });
  }
 },
 //打开支付方式弹窗
 choosePayWay: function() {
  var payWayList = this.data.payWayList
  var that = this;
  var rd_session = wx.getStorageSync('rd_session') || [];

  that.setData({
   payWayList: payWay
  });

  // 支付方式打开动画
  var animation = wx.createAnimation({
   duration: 200,
   timingFunction: 'ease-in-out',
   delay: 0
  });
  that.animation = animation;
  animation.translate(0, -285).step();
  that.setData({
   animationData: that.animation.export(),
  });
  that.setData({
   maskFlag: false,
  });
 },
 // 支付方式关闭方法
 closePayWay: function() {
  var that = this
  // 支付方式关闭动画
  that.animation.translate(0, 285).step();
  that.setData({
   animationData: that.animation.export()
  });
  that.setData({
   maskFlag: true
  });
 },
 // 获取输入的用餐人数
 getDinerNum: function(e) {
  var diner_num = e.detail.value;
  var cart = wx.getStorageSync('cart') || [];
  this.setData({
   diner_num: diner_num,
   // 按照人数算出价格
   diner_price: diner_num * cart[0].repastMoney
  })
 },
 // 获取备注信息
 getRemark: function(e) {
  var remarks = this.data.remarks;
  this.setData({
   remarks: e.detail.value
  })
 },
 //提交订单
 submitOrder: function(e) {
  var that = this;
  // var tableNum = that.data.tableNum;

  var arr = wx.getStorageSync('cart') || [];

  var goods_arr = [];
  arr.forEach(order => {
   console.log(order);
   var goods = new Object();
   goods.menuId = order.menuId;
   goods.menuName = order.menuName;
   goods.menuPictureUrl = order.menuPictureUrl;
   goods.menuDescription = order.menuDescription;
   goods.categoryName = order.categoryName;
  //  goods.repastStartTime = order.repastTime + ' ' + order.repastStarttime;
  //  goods.repastEndTime = order.repastTime + ' ' + order.repastEndtime;
   goods_arr.push(goods)
  })

  var repastStartTime = arr[0].repastTime + ' ' + arr[0].repastStarttime;
  var repastEndTime = arr[0].repastTime + ' ' + arr[0].repastEndtime;
  var day = arr[0].repastTime;
  var categoryType = arr[0].categoryType;

  var goods_josn = JSON.stringify(goods_arr);
  console.log(goods_josn)
  var remarks = this.data.remarks; //备注信息
  // 订单id
  var user = wx.getStorageSync('phone');
  var date = util.getCurrentMilliseconds();
  var payId = user + date;
  // 获取用户名和电话号码
  var buyer = wx.getStorageSync('wx_user');
  // 判断用户是否在内存中存在，若不存在，提示用户登录信息过期，请登录
  if (buyer == null || buyer == '') {
    wx.showToast({
      title: '登录信息过期，请登录！',
      icon: 'none',
      duration: 1000,
      success:function(){
        setTimeout(function () {
          //要延时执行的代码,延迟1s
          wx.navigateTo({
            url: '../login/login',
          })
        },1000)
      }
    })
  }
  var buyerName = buyer.name;
  var buyerPhone = buyer.iphone;
  // 用户id
  var wxUserId = buyer.id;
  // 订单状态, 默认为新下单
  var orderStatus = 0;
  // 支付状态, 默认未支付
  var payStatus = 0;
  // 就餐人数和价格
  var orderNum = this.data.diner_num;
  var orderPrice = this.data.diner_price;

  // 判断校验, 获取当前用户的余额
  var balancePrice = buyer.balance;
  if (balancePrice < orderPrice) {
    wx.showToast({
      title: '余额不足！',   
      icon: 'none',   
      duration: 2000
   })
   return;
  }

  wx.request({
   url: app.globalData.baseUrl + '/wechatprogram/ordermaster/add',
   method: "POST",
   header: {
    "Content-Type": "application/x-www-form-urlencoded"
   },
   data: {
    remarks: remarks,
    payId: payId,
    buyerName: buyerName,
    buyerPhone: buyerPhone,
    wxUserId: wxUserId,
    orderStatus: orderStatus,
    payStatus: payStatus,
    orderNum: orderNum,
    orderPrice: orderPrice,
    repastStartTime: repastStartTime,
    repastEndTime: repastEndTime,
    day: day,
    categoryType: categoryType,
    items: goods_josn
   },
   success: function(res) {
    // var rescode = res.data.code
    if (res.data.code == 0) {
      wx.setStorageSync('wx_user',  res.data.data);
     // 支付方式关闭动画
     that.animation.translate(0, 285).step();
     that.setData({
      animationData: that.animation.export()
     });
     that.setData({
      maskFlag: true
     });
     wx.showToast({
      title: '下单成功！',
      icon: 'success',
      duration: 1500,
      success:function(){
        setTimeout(function () {
          //要延时执行的代码
          wx.reLaunch({
            url: '../index/index',
          })
        },1500) //延迟时间
        
      }
     })
     // 提交成功后直接清空购物车
     wx.setStorageSync('cart', "")
   
    } else {
     // 支付方式关闭动画
     that.animation.translate(0, 285).step();
     that.setData({
      animationData: that.animation.export()
     });
     that.setData({
      maskFlag: true
     });
      wx.showToast({
        title: res.data.msg,   
        icon: 'none',   
        duration: 2000
     })
    }

   }
  })

 },


})